package servlet.car;


import service.GoodsService;
import servlet.user.LoginServlet;
import util.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebServlet("/AddCarServlet")
@MultipartConfig
public class AddCarServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        String userid = session.getAttribute("zhi").toString();
        String goods_pic = request.getParameter("goods_pic");
        String goodsprice = request.getParameter("goods_price");
        GoodsService goodsService = new GoodsService();
        String sum = goodsService.findnum(goods_pic,userid);
        DbUtil dbUtil = new DbUtil();
        if (sum != null) {
            int number = Integer.parseInt(sum);
            number++;
            double price = Double.parseDouble(goodsprice);
            String sql_add="update car set num= '"+number+"',goods_price = "+price*number+" where goods_pic='"+goods_pic+"'and user_id='"+userid+"'";
            System.out.println(sql_add);
            if (dbUtil.executeUpdate(sql_add) > 0){
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print("<script language='javascript'>  \n" +
                        "    alert('添加购物车成功！');  \n" +
                        "    window.location.href = '/GotoCarServlet';  \n" +
                        "</script>");
            }else {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print("<script language='javascript'>  \n" +
                        "    alert('添加购物车失败！');  \n" +
                        "    window.location.href = 'first.jsp';  \n" +
                        "</script>");
            }
        }else {
            String sql_add="insert into car(user_id,goods_pic,goods_price,num) values ('"+userid+"','"+goods_pic+"','"+goodsprice+"',"+1+")";
            System.out.println(sql_add);
            if (dbUtil.executeUpdate(sql_add) > 0){
                response.sendRedirect("first.jsp");
            }else {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print("<script language='javascript'>alert('库存不足，添加购物车失败'); window.location.href = 'first.jsp'</script>");
            }
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
